package com.rc.evcharger.service.enterprise;

import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.constant.WebConstant;
import com.rc.evcharger.mapper.enterprise.EnterpriseSubmemberShareMapper;
import com.rc.evcharger.mapper.member.MemberInfoMapper;
import com.rc.evcharger.mapper.order.OrderInfoMapper;
import com.rc.evcharger.model.enterprise.EnterpriseSubmemberShare;
import com.rc.evcharger.model.enterprise.EnterpriseSubmemberShareExample;
import com.rc.evcharger.model.member.MemberInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Create by Yang on 2021/5/26
 */
@Service
public class EnterpriseSubmemberShareServiceImpl implements EnterpriseSubmemberShareService {
    Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private EnterpriseSubmemberShareMapper enterpriseSubmemberShareMapper;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Override
    public EnterpriseSubmemberShareMapper getMapper() {
        return enterpriseSubmemberShareMapper;
    }


    @Override
    public EnterpriseSubmemberShare selectByTenantCodeAndMemberId(String tenantCode, Long memberId) {
        return enterpriseSubmemberShareMapper.selectByTenantCodeAndMemberId(tenantCode, memberId);
    }

    /**
     * 累计共享余额
     *
     * @param tenantCode
     * @param memberId
     * @param power
     * @param account
     */
    @Override
    public BigDecimal updatePowerOrAccountByOrderInfo(String tenantCode, Long memberId, BigDecimal power, BigDecimal account) {
        EnterpriseSubmemberShare enterpriseSubmemberShare = this.selectByTenantCodeAndMemberId(tenantCode, memberId);
        if (enterpriseSubmemberShare == null) {
            return null;
        }

        //共享余额限额
        BigDecimal shareAccount = enterpriseSubmemberShare.getShareAccount() == null ? BigDecimal.ZERO : enterpriseSubmemberShare.getShareAccount();
        enterpriseSubmemberShare.setShareAccount(shareAccount.add(account));
        if (enterpriseSubmemberShare.getFixedAccount().compareTo(enterpriseSubmemberShare.getShareAccount()) < 0) {
            enterpriseSubmemberShare.setShareAccount(enterpriseSubmemberShare.getFixedAccount());
        }

        //限制每日电量
        BigDecimal sharePower = enterpriseSubmemberShare.getSharePower() == null ? BigDecimal.ZERO : enterpriseSubmemberShare.getSharePower();
        enterpriseSubmemberShare.setSharePower(sharePower.add(power));
        if (enterpriseSubmemberShare.getFixedPower().compareTo(enterpriseSubmemberShare.getSharePower()) < 0) {
            enterpriseSubmemberShare.setSharePower(enterpriseSubmemberShare.getFixedPower());
        }
        enterpriseSubmemberShare.setLastUpdatedTime(new Date());

        this.updateByPrimaryKeySelective(enterpriseSubmemberShare);

        //返回剩余额度
        return enterpriseSubmemberShare.getFixedAccount().subtract(enterpriseSubmemberShare.getShareAccount());
    }

    @Override
    public BigDecimal selectMoneyByTenantCodeAndMemberId(String tenantCode, Long memberId) {
        EnterpriseSubmemberShare enterpriseSubmemberShare = enterpriseSubmemberShareMapper.selectByTenantCodeAndMemberId(tenantCode, memberId);
        if (enterpriseSubmemberShare == null) {
            logger.warn("共享余额 该会员:" + memberId + "没有共享余额记录");
            return null;
        }
        MemberInfo member = memberInfoMapper.selectByPrimaryKey(memberId);
//        if (member == null) {
//            logger.warn("该会员:" + memberId + "没有共享余额记录");
//            return null;
//        }
        //限额的有效金额必须大于2元
        if (enterpriseSubmemberShare.getFixedAccount().compareTo(new BigDecimal("1")) < 0) {
            logger.warn("共享余额 该会员:" + memberId + " 限额的有效金额必须大于2元");
            return null;
        }

        //查询共享余额
        //共享余额
        EnterpriseSubmemberShareExample enterpriseSubmemberShareExample = new EnterpriseSubmemberShareExample();
        enterpriseSubmemberShareExample.createCriteria().andTenantCodeEqualTo(tenantCode).andMemberIdEqualTo(memberId).andStatusEqualTo("1").andBeginTimeLessThan(new Date()).andEndTimeGreaterThanOrEqualTo(new Date());
        List<EnterpriseSubmemberShare> enterpriseSubmemberShares = enterpriseSubmemberShareMapper.selectByExample(enterpriseSubmemberShareExample);
        if (enterpriseSubmemberShares != null && enterpriseSubmemberShares.size() > 0) {
            if (enterpriseSubmemberShares.get(0).getSharePower().compareTo(enterpriseSubmemberShares.get(0).getFixedPower()) != -1) {
                logger.info("当前设置的共享余额的电量值不足,请选择其他支付类型！！");
                return null;
            }
            if (enterpriseSubmemberShares.get(0).getShareAccount().compareTo(enterpriseSubmemberShares.get(0).getFixedAccount()) != -1) {
                logger.info("当前设置的共享余额的金额不足,请选择其他支付类型！！");
                return null;
            }
        } else {
            logger.info("当前没有设置共享余额,请选择其他支付类型！！");
            return null;
        }

        MemberInfo parentMember = memberInfoMapper.selectByPrimaryKey(member.getEnterpriseMemberId());
        if (!member.getMemberType().equals(WebConstant.CON2 + "") && parentMember == null) {
            logger.warn("共享余额 该会员:" + memberId + "不是企业子会员");
            return null;
        }

        List<Long> memberInfos = memberInfoMapper.listSubMemberByEnterMemberId(parentMember.getMemberId());

        //查询正在使用共享余额充电的订单数
        Long count = orderInfoMapper.countByChargeType(SocketConstant.STR_CON2, memberInfos);
        if (count > 0) {
            count = count + 1;
        }
        if (parentMember.getJoinMemberAccount().getEnterpriseAccount().compareTo(new BigDecimal("50").multiply(BigDecimal.valueOf(count))) > 0) {
            //满足条件则返回可用额度
            return parentMember.getJoinMemberAccount().getEnterpriseAccount();
        }
        logger.warn("共享余额 该会员:" + memberId + "企业余额不足 ,对应的企业账号余额为:" + parentMember.getJoinMemberAccount().getEnterpriseAccount() + " " + count);
        return null;
    }
}
